package com.soft.jdbc.customer;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Scanner;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/6/6
 */
public class CustomerManage {
    private static DataSource dataSource;
    private static Scanner scanner = new Scanner(System.in);


    public static void main(String[] args) {
        try {
            Properties properties = new Properties();
            InputStream inputStream = CustomerManage.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

        while (true) {
            System.out.println("请选择操作：");
            System.out.println("1. 插入客户");
            System.out.println("2. 修改客户");
            System.out.println("3. 查询所有客户");
            System.out.println("4. 根据编号查询客户");
            System.out.println("5. 根据姓名查询客户");
            System.out.println("0. 退出");
            System.out.print("请输入选项：");

            int choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    insertCustomer();
                    break;
                case 2:
                    updateCustomer();
                    break;
                case 3:
                    queryAllCustomers();
                    break;
                case 4:
                    queryCustomerById();
                    break;
                case 5:
                    queryCustomerByName();
                    break;
                case 0:
                    System.out.println("程序退出！");
                    return;
                default:
                    System.out.println("无效选项，请重新输入！");
            }
        }
    }

    // 1. 插入客户
    private static void insertCustomer() {
        System.out.print("请输入编号：");
        int id = scanner.nextInt();

        System.out.print("请输入姓名：");
        String name = scanner.next();

        System.out.print("请输入邮箱：");
        String email = scanner.next();

        System.out.print("请输入生日（要求按xxxx-xx-xx格式）：");
        String birthdayStr = scanner.next();

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format.parse(birthdayStr);

            conn = dataSource.getConnection();
            String sql = "insert into customers(id, name, email, birthday) values (?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            pstmt.setString(2, name);
            pstmt.setString(3, email);
            pstmt.setDate(4, new java.sql.Date(date.getTime()));

            int count = pstmt.executeUpdate();
            if (count > 0) {
                System.out.println("插入成功！");
            } else {
                System.out.println("插入失败！");
            }
        } catch (ParseException | SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, null);
        }

    }

    // 2. 修改客户
    private static void updateCustomer() {
        System.out.print("请输入待修改的客户编号：");
        int id = scanner.nextInt();
        scanner.nextLine();

        System.out.print("请输入新的客户姓名：");
        String newName = scanner.next();

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = dataSource.getConnection();
            String sql = "update customers set name = ? where id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, newName);
            pstmt.setInt(2, id);

            int count = pstmt.executeUpdate();
            if (count > 0) {
                System.out.println("修改成功！");
            } else {
                System.out.println("修改失败，未找到指定编号的客户！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, null);
        }
    }

    // 3. 查询所有客户
    private static void queryAllCustomers() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = dataSource.getConnection();
            String sql = "select id, name, email, birthday from customers";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            printResult(rs);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, rs);
        }
    }

    // 4. 根据编号查询客户
    private static void queryCustomerById() {
        System.out.print("请输入编号：");
        int id = scanner.nextInt();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = dataSource.getConnection();
            String sql = "select id, name, email, birthday from customers where id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();

            printResult(rs);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, rs);
        }
    }

    // 5. 根据姓名查询客户
    private static void queryCustomerByName() {
        System.out.print("请输入姓名：");
        String name = scanner.next();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = dataSource.getConnection();
            String sql = "select id, name, email, birthday from customers where name = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            rs = pstmt.executeQuery();

            printResult(rs);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, rs);
        }
    }

    // 打印查询结果
    private static void printResult(ResultSet rs) throws SQLException {
        System.out.println("------------------------------------------------------------");
        System.out.println("编号\t\t姓名\t\t邮箱\t\t\t\t生日");

        boolean hasData = false;
        while (rs.next()) {
            hasData = true;
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String email = rs.getString("email");
            Date birthday = rs.getDate("birthday");

            System.out.println(id + "\t\t" + name + "\t\t" + email + "\t\t" + birthday);
        }

        if (!hasData) {
            System.out.println("查无此人");
        }
    }

    // 关闭资源
    private static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
